
package com.example.unique

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.GeocodeQuery
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.RegeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener
import com.google.android.gms.maps.model.LatLng

class MapSelectionActivity : AppCompatActivity() {

    private lateinit var locationClient: AMapLocationClient
    private lateinit var tvLocationStatus: TextView
    private lateinit var etAddress: EditText
    private lateinit var btnCheckIn: Button
    private lateinit var btnSearchAddress: Button
    private lateinit var geocodeSearch: GeocodeSearch

    // 目标打卡位置和半径（以米为单位）
    private val targetLocation = LatLng(30.565176, 104.2016) // 设置为预定义的目标位置
    private val targetRadius = 500.0 // 设置打卡范围半径，单位为米

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_map_selection)

        // 初始化UI组件
        tvLocationStatus = findViewById(R.id.tv_location_status)
        etAddress = findViewById(R.id.et_address)
        btnCheckIn = findViewById(R.id.btn_check_in)
        btnSearchAddress = findViewById(R.id.btn_search_address)

        // 请求定位相关的权限
        requestPermissions(
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), 1
        )

        // 初始化地理编码服务
        geocodeSearch = GeocodeSearch(this)
        geocodeSearch.setOnGeocodeSearchListener(object : OnGeocodeSearchListener {
            override fun onGeocodeSearched(result: GeocodeResult?, rCode: Int) {
                if (rCode == 1000 && result != null && result.geocodeAddressList.isNotEmpty()) {
                    val latLngPoint = result.geocodeAddressList[0].latLonPoint
                    val latitude = latLngPoint.latitude
                    val longitude = latLngPoint.longitude
                    Toast.makeText(this@MapSelectionActivity, "地址经纬度: $latitude, $longitude", Toast.LENGTH_LONG).show()
                } else {
                    Toast.makeText(this@MapSelectionActivity, "未找到指定地址", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult?, rCode: Int) {
                // 反向地理编码（非必须）
            }
        })

        // 查询按钮点击事件
        btnSearchAddress.setOnClickListener {
            val address = etAddress.text.toString()
            if (address.isNotEmpty()) {
                getLatLngFromAddress(address)
            } else {
                Toast.makeText(this, "请输入有效地址", Toast.LENGTH_SHORT).show()
            }
        }

        btnCheckIn.setOnClickListener {
            btnCheckIn.isEnabled = false // 禁用按钮，防止重复点击
            startLocation()
        }
    }

    // 启动定位
    private fun startLocation() {
        locationClient = AMapLocationClient(applicationContext)
        locationClient.setLocationListener(locationListener)

        val locationOption = AMapLocationClientOption().apply {
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            isNeedAddress = true
            isMockEnable = true  // 允许使用模拟位置
        }
        locationClient.setLocationOption(locationOption)

        // 开始定位
        locationClient.startLocation()
        Log.d("MapSelectionActivity", "开始定位")
    }

    // 计算当前位置和目标位置的距离
    private fun calculateDistance(currentLocation: LatLng, targetLocation: LatLng): Double {
        val results = FloatArray(1)
        android.location.Location.distanceBetween(
            currentLocation.latitude, currentLocation.longitude,
            targetLocation.latitude, targetLocation.longitude,
            results
        )
        return results[0].toDouble() // 返回距离，单位为米
    }

    // 获取指定地址的经纬度
    private fun getLatLngFromAddress(address: String) {
        val query = GeocodeQuery(address, "") // 第二个参数为城市代码，可选
        geocodeSearch.getFromLocationNameAsyn(query)
    }

    // 定位监听器
    private val locationListener = AMapLocationListener { location ->
        btnCheckIn.isEnabled = true // 恢复按钮可点击
        if (location != null && location.errorCode == 0) {
            // 获取详细地理信息
            val locationInfo = "位置: ${location.country} ${location.province} ${location.city} ${location.district} ${location.street} ${location.streetNum}"
            tvLocationStatus.text = locationInfo

            val currentLatLng = LatLng(location.latitude, location.longitude)

            // 进行距离检查
            val distance = calculateDistance(currentLatLng, targetLocation)
            if (distance <= targetRadius) {
                Toast.makeText(this, "您在目标范围内！", Toast.LENGTH_SHORT).show()
                // 返回打卡成功的结果
                val data = Intent().apply {
                    putExtra("check_in_status", "success")
                }
                setResult(Activity.RESULT_OK, data)
                finish()
            } else {
                Toast.makeText(this, "不在目标范围内，距离目标：${"%.2f".format(distance)}米", Toast.LENGTH_SHORT).show()
            }
        } else {
            Log.e("MapSelectionActivity", "定位失败，错误码：${location.errorCode}, 错误信息：${location.errorInfo}")
            Toast.makeText(this, "定位失败，请检查权限设置", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        locationClient.stopLocation()
        locationClient.onDestroy()
        super.onDestroy()

    }
}
